package com.park.web.controller.pub;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.park.client.model.article.ArticleCollectModel;
import com.park.client.model.article.ArticleCommentModel;
import com.park.client.model.article.ArticleModel;
import com.park.client.model.news.NewsModel;
import com.park.client.model.pub.SensitiveWordModel;
import com.park.client.model.user.UserAttentionModel;
import com.park.client.model.user.UserModel;
import com.park.client.service.article.ArticleCollectService;
import com.park.client.service.article.ArticleCommentService;
import com.park.client.service.article.ArticleService;
import com.park.client.service.news.NewsService;
import com.park.client.service.pub.SensitiveWordService;
import com.park.client.service.user.UserAttentionService;
import com.park.common.constant.Constant;
import com.park.common.util.Page;
import com.park.common.util.Result;
import com.park.web.contant.Global;
import com.park.web.controller.BaseController;
import com.park.web.util.SessionUtil;

@Controller
@RequestMapping("/public/news")
public class PublicNewsController extends BaseController{

	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleCollectService articleCollectService;
	@Autowired
	private ArticleCommentService articleCommentService;
	@Autowired
	private SensitiveWordService sensitiveWordService;
	@Autowired
	private UserAttentionService userAttentionService;
	@Autowired
	private NewsService newsService;
	/**
	 * 资讯详情
	 */
	@RequestMapping("detail/{id}")
	public String detail(@PathVariable("id")Long id,HttpServletRequest request){
			NewsModel news = newsService.selectByPrimaryKey(id);
			request.setAttribute("news", news);
			return Global.PUBLIC_PATH+"news/newsDetail";
	}
	
	@RequestMapping("newsList")
	public String newsList(@RequestParam(name="pageNow",defaultValue="1")Integer pageNow,HttpServletRequest request){
		NewsModel news = new NewsModel();
		Integer total = newsService.selectTotal(news);
		Page page = new Page(pageNow,total,10);
		news.setStartPos(page.getStartPos());
		news.setPageSize(page.getPageSize());
		List<NewsModel> newsList = newsService.selectPagination(news);
		request.setAttribute("newsList", newsList);
		request.setAttribute("page", page);
		return Global.PUBLIC_PATH+"news/newsList";
	}
	
	/**
	 *文章支持、吐槽、收藏
	 */
	@RequestMapping("view")
	@ResponseBody
	public Result<ArticleModel> view(Long id, Integer type,HttpServletRequest request,HttpSession session){
		Result<ArticleModel> result = new Result<>(true);
		UserModel user = SessionUtil.getSessionUser(session);
		if(user == null){
			result.setSuccess(Constant.FAIL);
			result.setCode(Constant.NOT_LOGGED102);
			result.setMessage(Constant.NOT_LOGGED_MSG);
			return result;
		}
		ArticleModel article = articleService.selectByPrimaryKey(id);
		switch (type) {
			case 1://支持
				return support(article);
			case 2://吐槽
				return oppose(article);
			default://收藏
				return collect(article, user);
		}
	}
	
	/**
	 * 支持
	 * @return
	 */
	private Result<ArticleModel> support(ArticleModel article){
		Result<ArticleModel> result = new Result<>(true);
		try {
			article.setSupportNum(article.getSupportNum()+1);
			articleService.updateByPrimaryKeySelective(article);
			result.setObj(article);
		} catch (Exception e) {
			result.setSuccess(Constant.FAIL);
			result.setMessage(Constant.FAIL_MSG_ZHICHI);
		}
		return result;
	}
	
	/**
	 * 吐槽
	 * @return
	 */
	private Result<ArticleModel> oppose(ArticleModel article){
		Result<ArticleModel> result = new Result<>(true);
		try {
			article.setOpposeNum(article.getOpposeNum()+1);
			articleService.updateByPrimaryKeySelective(article);
			result.setObj(article);
		} catch (Exception e) {
			result.setSuccess(Constant.FAIL);
			result.setMessage(Constant.FAIL_MSG_TUCAO);
		}
		return result;
	}
	
	/**
	 *收藏
	 * @return
	 */
	private Result<ArticleModel> collect(ArticleModel article,UserModel user){
		Result<ArticleModel> result = new Result<>(true);
		try {
			ArticleCollectModel collect = new ArticleCollectModel();
			collect.setCreater(user.getId());
			collect.setArticleId(article.getId());
			ArticleCollectModel newCollect = articleCollectService.selectIsExists(collect);
			if(newCollect == null){//没收藏过、收藏过提示不再收藏	
				article.setCollectNum(article.getCollectNum()+1);
				articleService.updateByPrimaryKeySelective(article);
				articleCollectService.insert(collect);
				result.setObj(article);
			}else{
				result.setSuccess(Constant.FAIL);
				result.setMessage(Constant.FAIL_COLLECTION);
			}
			result.setObj(article);
		} catch (Exception e) {
			result.setSuccess(Constant.FAIL);
			result.setMessage(Constant.FAIL_COLLECTION);
		}
		return result;
	}
	
	/**
	 *文章评论
	 */
	@RequestMapping("articleComment")
	@ResponseBody
	public Result<ArticleCommentModel> articleComment(@RequestParam("commentContent") String commentContent,@RequestParam("articleId") Long articleId,HttpServletRequest request,HttpSession session){
		Result<ArticleCommentModel> result = new Result<>(true);
		try {
			UserModel user = SessionUtil.getSessionUser(session);
			if(user == null){
				result.setSuccess(Constant.FAIL);
				result.setCode(Constant.NOT_LOGGED102);
				result.setMessage(Constant.NOT_LOGGED_MSG);
				return result;
			}
			ArticleCommentModel c = new ArticleCommentModel();
			c.setCreater(user.getId());
			c.setArticleId(articleId);
			ArticleCommentModel comment = articleCommentService.selectIsExist(c);
			if(comment != null){
				result.setSuccess(Constant.FAIL);
				result.setMessage(Constant.HAS_COMMENT_MSG);//你已评论过，请勿重复评论!
			}
			
			comment = new ArticleCommentModel();
			//过滤敏感词
			List<SensitiveWordModel> words = sensitiveWordService.selectAll();
			for (SensitiveWordModel word : words) {
				commentContent = commentContent.replaceAll(word.getWord(), "***");
			}
			comment.setCommentContent(commentContent);
			comment.setCommentDate(new Date());
			comment.setCreater(user.getId());
			comment.setArticleId(articleId);
			articleCommentService.insertSelective(comment);
			result.setObj(comment);
			result.setMessage(Constant.SUCCESS_COMMENT_MSG);
		} catch (Exception e) {
			result.setSuccess(Constant.FAIL);
			result.setMessage(Constant.FAIL_COMMENT_MSG);
		}
		return result;
	}
	
	/**
	 *给文章作者发私信
	 */
	@RequestMapping("sendPrivateMsg")
	@ResponseBody
	public Result<Boolean> sendPrivateMsg(Integer userId,HttpServletRequest request,HttpSession session){
		Result<Boolean> result = new Result<>(true);
		UserModel user = (UserModel) session.getAttribute("user");
		if(user != null){
			result.setMessage(Constant.SUCCESS_MSG);
			result.setSuccess(Constant.SUCCESS);
		}else{//未登录
			result.setMessage(Constant.NOT_LOGGED_MSG);
			result.setSuccess(Constant.FAIL);
		}
		return result;
	}
	
	/**
	 * 关注文章作者
	 */
	@RequestMapping("attentionArticleAuth")
	@ResponseBody
	public Result<Boolean> attentionArticleAuth(Long userId,HttpServletRequest request,HttpSession session){
		Result<Boolean> result = new Result<>(true);
		UserModel user = (UserModel) session.getAttribute("user");
		if(user == null){
			result.setMessage(Constant.NOT_LOGGED_MSG);
			result.setCode(Constant.NOT_LOGGED102);
			result.setSuccess(Constant.FAIL);
			return result;
		}
		if(Objects.equals(user.getId(),userId)){//自己关注自己
			result.setMessage(Constant.FAIL_ATENTIONSELF_MSG);
			result.setSuccess(Constant.FAIL);
		}else{
			UserAttentionModel userAttention = new UserAttentionModel();
			userAttention.setUserAttentionId(userId);
			userAttention.setCreater(user.getId());
			UserAttentionModel f = userAttentionService.selectHasExists(userAttention);
			if(f == null){//没有收藏过
				boolean success =  userAttentionService.insertSelective(userAttention);
				if(success){//成功
					result.setMessage(Constant.SUCCESS_MSG);
					result.setSuccess(Constant.SUCCESS);
				}else{//失败
					result.setMessage(Constant.FAIL_MSG);
					result.setSuccess(Constant.FAIL);
				}
			}else{//已经收藏过
				result.setMessage(Constant.FAIL103_2_MSG);
				result.setSuccess(Constant.FAIL);
			}
		}
		return result;
	}
}
